package com.atguigu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.bean.TrafficIsNewPageViewBean;
import com.atguigu.realtime.bean.TrafficPageViewBean;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @auther yuzehua
 * @date 2022/10/27 - 10:51
 */
public class Dws_TrafficIsNewPageViewWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_TrafficIsNewPageViewWindow().init(
                2024,
                2,
                "Dws_TrafficIsNewPageViewWindow",
                Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1.封装成一个POJO
        SingleOutputStreamOperator<TrafficIsNewPageViewBean> beanStream = parseToPojo(stream);
        // 2.开窗聚合
        SingleOutputStreamOperator<TrafficIsNewPageViewBean> resultStream = windowAndAgg(beanStream);
        // 3. 写出到 clickhouse 中
        writeToClickhouse(resultStream);
    }

    private void writeToClickhouse(SingleOutputStreamOperator<TrafficIsNewPageViewBean> resultStream) {
        resultStream
                .addSink(FlinkSinkUtil.getClickHouseSink("dws_traffic_is_new_page_view_window",
                        TrafficIsNewPageViewBean.class
                ));
    }

    private SingleOutputStreamOperator<TrafficIsNewPageViewBean> windowAndAgg(SingleOutputStreamOperator<TrafficIsNewPageViewBean> beanStream) {
        return beanStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<TrafficIsNewPageViewBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner(new SerializableTimestampAssigner<TrafficIsNewPageViewBean>() {
                                    @Override
                                    public long extractTimestamp(TrafficIsNewPageViewBean element, long recordTimestamp) {
                                        return element.getTs();
                                    }
                                }))
                .keyBy(TrafficIsNewPageViewBean::getIsNew)
                .window(TumblingEventTimeWindows.of(Time.seconds(3)))
                .reduce(new ReduceFunction<TrafficIsNewPageViewBean>() {
                    @Override
                    public TrafficIsNewPageViewBean reduce(TrafficIsNewPageViewBean value1, TrafficIsNewPageViewBean value2) throws Exception {
                        value1.setUvCt(value1.getUvCt() + value2.getUvCt());
                        value1.setPvCt(value1.getPvCt() + value2.getPvCt());
                        value1.setDurSum(value1.getDurSum() + value2.getDurSum());
                        return value1;
                    }
                }, new ProcessWindowFunction<TrafficIsNewPageViewBean, TrafficIsNewPageViewBean, Long, TimeWindow>() {
                    @Override
                    public void process(Long aLong, Context context, Iterable<TrafficIsNewPageViewBean> elements, Collector<TrafficIsNewPageViewBean> out) throws Exception {
                        TrafficIsNewPageViewBean bean = elements.iterator().next();
                        Long uvCt = bean.getUvCt();
                        if (uvCt != 0) {
                            bean.setDurAvgSum(bean.getDurSum() / uvCt);
                            bean.setPvAvgCt(bean.getPvCt() / uvCt);
                        } else {
                            bean.setDurAvgSum(bean.getDurSum());
                            bean.setPvAvgCt(bean.getPvCt());
                        }

                        bean.setStt(AtguiguUtil.toDatTime(context.window().getStart()));
                        bean.setEdt(AtguiguUtil.toDatTime(context.window().getEnd()));

                        bean.setTs(System.currentTimeMillis());
                        out.collect(bean);
                    }
                });
    }

    private SingleOutputStreamOperator<TrafficIsNewPageViewBean> parseToPojo(DataStreamSource<String> stream) {
        return stream
                .map(JSON::parseObject)
                .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
                .map(new RichMapFunction<JSONObject, TrafficIsNewPageViewBean>() {

                    private ValueState<String> dateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        // 给状态设置ttl
                        ValueStateDescriptor<String> desc = new ValueStateDescriptor<>("dateState", String.class);
                        desc.enableTimeToLive(new StateTtlConfig.Builder(org.apache.flink.api.common.time.Time.days(1)).build());
                        dateState = getRuntimeContext().getState(desc);
                    }

                    @Override
                    public TrafficIsNewPageViewBean map(JSONObject obj) throws Exception {

                        JSONObject common = obj.getJSONObject("common");
                        JSONObject page = obj.getJSONObject("page");

                        Long isNew = common.getLong("is_new");

                        Long ts = obj.getLong("ts");

                        Long pvCt = 1L;
                        Long durSum = page.getLong("during_time");

                        Long uvCt = 0L;

                        // 状态中存储年月日, 如果来的数据的日期和状态不一样, 就是当天第一条 uvCt=1 更新状态,
                        // 否则就不是第一条
                        String date = dateState.value();
                        String today = AtguiguUtil.toDate(ts);
                        if (!today.equals(date)) {
                            // 更新状态
                            dateState.update(today);
                            uvCt = 1L;
                        }

                        Long pvAvgCt = 0L;
                        Long durAvgSum = 0L;


                        return new TrafficIsNewPageViewBean("", "",isNew,
                                uvCt, pvCt,pvAvgCt, durSum,durAvgSum,
                                ts
                        );
                    }
                });
    }

}
